/*=============================================================================

  Library: HMPBundleFrame

  Copyright (c) German Cancer Research Center,
    Division of Medical and Biological Informatics

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.

=============================================================================*/

#include <QMutex>

#include "BundleFrameworkContext_p.h"
#include "Bundle_p.h"
#include "BundleConstants.h"
#include "ServiceFactory.h"
#include "IServiceRegistration.h"
#include "ServiceRegistration_p.h"
#include "Services_p.h"
#include "ServiceSlotEntry_p.h"

#include <stdexcept>

//----------------------------------------------------------------------------
IServiceRegistration::IServiceRegistration()
  : d_ptr(0)
{

}

//----------------------------------------------------------------------------
IServiceRegistration::IServiceRegistration(const IServiceRegistration& reg)
  : d_ptr(reg.d_ptr)
{
  if (d_func()) d_func()->ref.ref();
}

//----------------------------------------------------------------------------
IServiceRegistration::IServiceRegistration(ServiceRegistrationPrivate* registrationPrivate)
  : d_ptr(registrationPrivate)
{
  if(d_func()) d_func()->ref.ref();
}

//----------------------------------------------------------------------------
IServiceRegistration::IServiceRegistration(BundlePrivate* plugin, QObject* service,
                    const Dictionary& props)
  : d_ptr(new ServiceRegistrationPrivate(plugin, service, props))
{

}

//----------------------------------------------------------------------------
IServiceRegistration::operator bool() const
{
  return d_func();
}

//----------------------------------------------------------------------------
IServiceRegistration& IServiceRegistration::operator=(int null)
{
  if (null == 0)
  {
    if (d_func() && !d_func()->ref.deref())
    {
      delete d_ptr;
    }
    d_ptr = 0;
  }
  return *this;
}

//----------------------------------------------------------------------------
IServiceRegistration::~IServiceRegistration()
{
  if (d_func() && !d_func()->ref.deref())
    delete d_ptr;
}

//----------------------------------------------------------------------------
IServiceReference IServiceRegistration::getServiceReference() const
{
  Q_D(const ServiceRegistration);

  if (!d) throw IllegalStateException("ServiceRegistration object invalid");
  if (!d->available) throw IllegalStateException("Service is unregistered");

  return d->reference;
}

//----------------------------------------------------------------------------
void IServiceRegistration::setProperties(const Dictionary& props)
{
  Q_D(ServiceRegistration);
  if (!d) throw IllegalStateException("ServiceRegistration object invalid");

  QMutexLocker lock(&d->eventLock);

  QSet<ServiceSlotEntry> before;
  // TBD, optimize the locking of services
  {
    QMutexLocker lock2(&d->plugin->fwCtx->globalFwLock);
    QMutexLocker lock3(&d->propsLock);

    if (d->available)
    {
      // NYI! Optimize the MODIFIED_ENDMATCH code
      int old_rank = d->properties.value(BundleConstants::SERVICE_RANKING).toInt();
      before = d->plugin->fwCtx->listeners.getMatchingServiceSlots(d->reference, false);
      QStringList classes = d->properties.value(BundleConstants::OBJECTCLASS).toStringList();
      qlonglong sid = d->properties.value(BundleConstants::SERVICE_ID).toLongLong();
      d->properties = Services::createServiceProperties(props, classes, sid);
      int new_rank = d->properties.value(BundleConstants::SERVICE_RANKING).toInt();
      if (old_rank != new_rank)
      {
        d->plugin->fwCtx->services->updateServiceRegistrationOrder(*this, classes);
      }
    }
    else
    {
      throw IllegalStateException("Service is unregistered");
    }
  }
  d->plugin->fwCtx->listeners.serviceChanged(
      d->plugin->fwCtx->listeners.getMatchingServiceSlots(d->reference),
      ServiceEvent(ServiceEvent::MODIFIED, d->reference), before);

  d->plugin->fwCtx->listeners.serviceChanged(
      before,
              ServiceEvent(ServiceEvent::MODIFIED_ENDMATCH, d->reference));
}

const Dictionary &IServiceRegistration::getProperties() const
{
    Q_D(const ServiceRegistration);

    //prosLock const类型，读取数据，暂时不加锁
    //QMutexLocker lock(&d->propsLock);

    static QHash<QString, QVariant> pro;
    pro = d->properties.getProperties();

    return pro;
}

//----------------------------------------------------------------------------
void IServiceRegistration::unregister()
{
  Q_D(ServiceRegistration);
  if (!d) throw IllegalStateException("ServiceRegistration object invalid");

  if (d->unregistering) return; // Silently ignore redundant unregistration.
  {
    QMutexLocker lock(&d->eventLock);
    if (d->unregistering) return;
    d->unregistering = true;

    if (d->available)
    {
      if (d->plugin)
      {
        d->plugin->fwCtx->services->removeServiceRegistration(*this);
      }
    }
    else
    {
      throw IllegalStateException("Service is unregistered");
    }
  }

  if (d->plugin)
  {
     d->plugin->fwCtx->listeners.serviceChanged(
         d->plugin->fwCtx->listeners.getMatchingServiceSlots(d->reference),
         ServiceEvent(ServiceEvent::UNREGISTERING, d->reference));
  }

  {
    QMutexLocker lock(&d->eventLock);
    {
      QMutexLocker lock2(&d->propsLock);
      d->available = false;
      if (d->plugin)
      {
        for (QHashIterator<QSharedPointer<IBundle>, QObject*> i(d->serviceInstances); i.hasNext();)
        {
          QObject* obj = i.next().value();
          try
          {
            // NYI, don't call inside lock
            qobject_cast<ServiceFactory*>(d->service)->ungetService(i.key(),
                                                                       *this,
                                                                       obj);
          }
          catch (const Exception& ue)
          {
            BundleFrameworkEvent pfwEvent(BundleFrameworkEvent::PLUGIN_ERROR, d->plugin->q_func(), ue);
            d->plugin->fwCtx->listeners.emitFrameworkEvent(pfwEvent);
          }
        }
      }
      d->plugin = 0;
      d->dependents.clear();
      d->service = 0;
      d->serviceInstances.clear();
      d->reference = 0;
      d->unregistering = false;
    }
  }
}

//----------------------------------------------------------------------------
bool IServiceRegistration::operator<(const IServiceRegistration& o) const
{
  Q_D(const ServiceRegistration);
  if (!d) return true;
  return d->reference <(o.d_func()->reference);
}

//----------------------------------------------------------------------------
bool IServiceRegistration::operator==(const IServiceRegistration& registration) const
{
  Q_D(const ServiceRegistration);
  return d == registration.d_func();
}

//----------------------------------------------------------------------------
IServiceRegistration& IServiceRegistration::operator=(const IServiceRegistration& registration)
{
  ServiceRegistrationPrivate* curr_d = d_func();
  d_ptr = registration.d_ptr;
  if (d_ptr) d_ptr->ref.ref();

  if (curr_d && !curr_d->ref.deref())
    delete curr_d;

  return *this;
}

//----------------------------------------------------------------------------
uint qHash(const IServiceRegistration& serviceReg)
{
  return qHash(serviceReg.d_func());
}
